<template>
  <el-container v-if="show">
    <el-header style="margin-top: 60px">
      <el-row>
        <el-col :span="18" :offset="3" style="border-bottom: 1px solid #f5f5f5">
          <span class="startExam">虚拟考核</span>
<!--          <el-button type="warning" round-->
<!--                     style="background-color: #ffd550;float: right;color: black;font-weight: 800"-->
<!--                     @click="uploadExamToAdmin"-->
<!--          >提交试卷-->
<!--          </el-button>-->
        </el-col>
      </el-row>
      <br>
      <el-row>
        <el-col :offset="3" :span="4">总题目数<span v-html="'\u00a0\u00a0\u00a0'"/>{{questionInfo.length}}</el-col>
        <el-col :span="4">已完成<span v-html="'\u00a0\u00a0\u00a0'"/>{{examInfo.dones}}</el-col>
        <el-col :span="5">进度<span v-html="'\u00a0\u00a0\u00a0'"/>{{parseInt(examInfo.dones / questionInfo.length * 100) + '%' }}</el-col><el-col :span="1"></el-col>
        <el-col :span="5">正确率<span v-html="'\u00a0\u00a0\u00a0'"/>{{examInfo.dones > 0 ? parseInt(examInfo.rights / examInfo.dones * 100) + '%' : '0%' }}</el-col><el-col :span="1"></el-col>
      </el-row>
    </el-header>

    <el-main>
      <el-row>
        <el-col :span="18" :offset="3">
          <el-col :span="16">
            <el-card style="min-height: 500px">
              <!--题目信息-->
              <div>
                <i class="num">{{ curIndex + 1 }}</i>
                <span v-if="questionInfo[curIndex].question.type === 1">【单选题】</span>
                <span v-else-if="questionInfo[curIndex].question.type === 2">【多选题】</span>
                <span v-else-if="questionInfo[curIndex].question.type === 3">【判断题】</span>
                <span v-else>【填空题】</span>
                <span>{{ questionInfo[curIndex].question.content }}:</span>
              </div>
              <!--题目中的配图-->
              <img v-for="url in questionInfo[curIndex].images" :src="url" title="点击查看大图" alt="题目图片"
                   style="width: 100px;height: 100px;cursor: pointer" @click="showBigImg(url)"
              >

              <!--单选 和 判断 的答案列表-->
              <div style="margin-top: 25px"
                   v-show="questionInfo[curIndex].question.type === 1 || questionInfo[curIndex].question.type === 3"
              >
                <div class="el-radio-group">
                  <label v-for="(item,index) in questionInfo[curIndex].question.option"
                         @click="checkSingleAnswer(index ,item ,$event)"
                         :class="getOptClass(curIndex ,item)"
                  >
                    <span>{{ item }}</span>
                    <img style="position: absolute;left:100%;top:50%;transform: translateY(-50%);
                  width: 40px;height: 40px;float: right;cursor: pointer;" title="点击查看大图"
                         v-if="item.images !== null"
                         v-for="i2 in item.images" :src="i2" alt="" @mouseover="showBigImg(i2)"
                    >
                  </label>
                </div>
                <div v-if="questionInfo[curIndex].done">
                  <span>答案：{{ questionInfo[curIndex].question.answer }}</span>
                </div>
              </div>

              <!--多选的答案列表-->
              <div style="margin-top: 25px" v-show="questionInfo[curIndex].question.type === 2">
                <div class="el-radio-group">
                  <label v-for="(item,index) in questionInfo[curIndex].question.option"
                         @click="selectedMultipleAnswer(item)"
                         :class="getOptClass(curIndex ,item)"
                  >
                    <span>{{ item }}</span>
                    <img style="position: absolute;left:100%;top:50%;transform: translateY(-50%);
                  width: 40px;height: 40px;float: right;cursor: pointer;" title="点击查看大图"
                         v-if="item.images !== null"
                         v-for="i2 in item.images" :src="i2" alt="" @mouseover="showBigImg(i2)"
                    >
                  </label>
                </div>
                <div v-if="questionInfo[curIndex].done">
                  <span>答案：{{ questionInfo[curIndex].question.answer.split("&") }}</span>
                </div>
              </div>

              <!--简答题的答案-->
              <div style="margin-top: 25px" v-show="questionInfo[curIndex].question.type === 4">
                <el-input
                  type="textarea"
                  :rows="8"
                  placeholder="请输入答案"
                  v-model="userAnswer[curIndex]"
                  :disabled="questionInfo[curIndex].done"
                >
                </el-input>
                <div v-if="questionInfo[curIndex].done">
                  <span>答案：{{ questionInfo[curIndex].question.answer }}</span>
                </div>
                <div v-else>
                  <span>多个空的答案用回车分隔</span>
                </div>
              </div>

              <!--上一题 下一题-->
              <div style="margin-top: 25px">
                <el-button type="primary" icon="el-icon-back" :disabled="curIndex<1" @click="curIndex--">上一题</el-button>
                <el-button type="primary" icon="el-icon-right" :disabled="curIndex>=questionInfo.length-1"
                           @click="nextQuestion"
                >下一题</el-button>
                <el-button type="primary" icon="el-icon-right" v-if="curIndex>=questionInfo.length-1"
                           @click="nextQuestion"
                >提交</el-button>
              </div>

            </el-card>
          </el-col>

          <el-col :span="7" :offset="1">
            <!--答题卡卡片-->
            <el-card>
              <div>
                <p style="font-size: 18px;">答题卡</p>
                <div style="margin-top: 25px">
                  <span
                    style="background-color: rgb(238,238,238);padding: 5px 10px 5px 10px;margin-left: 15px"
                  >未作答</span>
                  <span style="background-color: rgb(87,148,247);color: white;
                padding: 5px 10px 5px 10px;margin-left: 15px"
                  >已作答</span>
                </div>
              </div>

              <!--单选的答题卡-->
              <div style="margin-top: 25px">
                <p style="font-size: 18px;">题号</p>
                <el-button style="margin-top: 10px;margin-left: 15px" size="mini"
                           :class="getQuestionClass(item - 1)"
                           v-for="item in questionInfo.length" :key="item" @click="curIndex = item-1"
                >{{ item }}
                </el-button>
              </div>
            </el-card>
          </el-col>

        </el-col>
      </el-row>
      <video id="video" muted="muted" style="float:right;position: fixed;top: 80%;left: 85%" width="200px"
             height="200px" autoplay="autoplay"
      ></video>
      <canvas id="canvas" hidden width="200px" height="200px"></canvas>
    </el-main>
    <!--图片回显-->
    <el-dialog :visible.sync="bigImgDialog" @close="bigImgDialog = false">
      <img style="width: 100%" :src="bigImgUrl">
    </el-dialog>
    <!-- 考试结果 -->
    <el-dialog :visible.sync="examResult.show" @close="examResultClose">
      <el-form ref="form" label-width="80px">
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="examInfo.examName" maxlength="30"/>
        </el-form-item>
        <el-form-item label="答题时长" prop="time">
          <el-input v-model="examResult.time" maxlength="30"/>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input v-model="examResult.score" maxlength="30"/>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-container>

</template>

<script>

// import exam from '@/api/exam'
// import question from '@/api/question'
// import ossUtils from '@/api/ossUtils'

import { info, questionList, submitAnswer } from '@/api/exam/unreal'

export default {
  name: 'ExamPage',
  data() {
    return {
      //当前考试的信息
      examInfo: {
        examName: ''
      },
      //当前的考试题目
      questionInfo: [
        {
          type: ''
        }
      ],

      startTime: new Date().getTime() / 1000,

      //当前题目的索引值
      curIndex: 0,
      //控制大图的对话框
      bigImgDialog: false,
      //当前要展示的大图的url
      bigImgUrl: '',
      //用户选择的答案
      userAnswer: [],
      //页面数据加载
      loading: {},
      //页面绘制是否开始
      show: false,
      //答案的选项名abcd数据
      optionName: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      //摄像头对象
      mediaStreamTrack: null,
      //诚信照片的url
      takePhotoUrl: [],
      //摄像头是否开启
      cameraOn: false,

      examResult: {
        show: false,
        time: 0,
        score: 0
      }
    }
  },
  created() {
    this.getExamInfo()
  },
  mounted() {
    //关闭浏览器窗口的时候移除 localstorage的时长
    var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf('Opera') > -1 //判断是否Opera浏览器
    var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera //判断是否IE浏览器
    var isIE11 = userAgent.indexOf('rv:11.0') > -1 //判断是否是IE11浏览器
    var isEdge = userAgent.indexOf('Edge') > -1 && !isIE //判断是否IE的Edge浏览器
    if (!isIE && !isEdge && !isIE11) {//兼容chrome和firefox
      var _beforeUnload_time = 0, _gap_time = 0
      var is_fireFox = navigator.userAgent.indexOf('Firefox') > -1//是否是火狐浏览器
      window.onunload = function() {
        _gap_time = new Date().getTime() - _beforeUnload_time
        if (_gap_time <= 5) {
          localStorage.removeItem('examDuration' + this.examInfo.examId)
        } else {//谷歌浏览器刷新
        }
      }
      window.onbeforeunload = function() {
        _beforeUnload_time = new Date().getTime()
        if (is_fireFox) {//火狐关闭执行

        } else {//火狐浏览器刷新
        }
      }
    }
  },
  methods: {
    //查询当前考试的信息
    getExamInfo() {
      info().then((resp) => {
        if (resp.data) {
          this.examInfo = resp.data
        }
        this.getQuestionInfo(this.examInfo.id)

        // this.loading.close()
        this.show = true
      })
    },
    //查询考试的题目信息
    async getQuestionInfo(id) {
      await questionList().then(resp => {
        if (resp.code === 200) {
          let data = resp.data
          this.questionInfo = data
          //重置问题的顺序 单选 多选 判断 简答
          this.questionInfo = this.questionInfo.sort(function(a, b) {
            return a.question.id - b.question.id
          })
          for(let i = 0 ; i < this.questionInfo.length; i++){
            if(this.questionInfo[i].done){
              this.userAnswer[i] = this.questionInfo[i].userAnswer;
            }
          }
        }
      })
    },
    //点击展示高清大图
    showBigImg(url) {
      this.bigImgUrl = url
      this.bigImgDialog = true
    },
    //检验单选题的用户选择的答案
    checkSingleAnswer(index ,item ,el) {
      if(!this.questionInfo[this.curIndex].done){
        this.$set(this.userAnswer, this.curIndex, item)
      }
    },
    //多选题用户的答案选中
    selectedMultipleAnswer(index) {
      if (this.userAnswer[this.curIndex] === undefined) {//当前是多选的第一个答案
        this.$set(this.userAnswer, this.curIndex, index)
      } else if (String(this.userAnswer[this.curIndex]).split(',').includes(index + '')) {//取消选中
        let newArr = []
        String(this.userAnswer[this.curIndex]).split(',').forEach(item => {
          if (item !== '' + index) newArr.push(item)
        })
        if (newArr.length === 0) {
          this.$set(this.userAnswer, this.curIndex, undefined)
        } else {
          this.$set(this.userAnswer, this.curIndex, newArr.join(','))
          //答案格式化顺序DBAC -> ABCD
          this.userAnswer[this.curIndex] = String(this.userAnswer[this.curIndex]).split(',').sort(function(a, b) {
            return a - b
          }).join(',')
        }
      } else if (!((this.userAnswer[this.curIndex] + '').split(',').includes(index + ''))) {//第n个答案
        this.$set(this.userAnswer, this.curIndex, this.userAnswer[this.curIndex] += ',' + index)
        //答案格式化顺序DBAC -> ABCD
        this.userAnswer[this.curIndex] = String(this.userAnswer[this.curIndex]).split(',').sort(function(a, b) {
          return a - b
        }).join(',')
      }
    },

    getCostTime() {
      return new Date().getTime() / 1000 - this.startTime
    },
    async uploadExamToAdmin() {
      // 标记题目是否全部做完
      let flag = true
      for (let i = 0; i < this.userAnswer.length; i++) {// 检测用户是否题目全部做完
        if (this.userAnswer[i] === undefined) {
          flag = false
        }
      }
      // 如果用户所有答案的数组长度小于题目长度,这个时候也要将标志位置为false
      if (this.userAnswer.length < this.questionInfo.length) {
        flag = false
      }
      //题目未做完
      if (!flag) {
        // if (this.userAnswer.some((item) => item === undefined)) {
        let that = this
        this.$confirm('当前试题暂未做完, 是否继续提交o(╥﹏╥)o ?', 'Tips', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {}
          data.answers = this.userAnswer
          data.examId = this.examInfo.id
          data.time = this.getCostTime()
          console.log(data)
          submitPaper(data).then((resp) => {
            if (resp.code === 200) {
              this.$notify({
                title: 'Tips',
                message: '考试结束',
                type: 'success',
                duration: 2000
              })
              this.examResult.time = data.time
              this.examResult.score = resp.data
              this.examResult.show = true
            }
          })
        }).catch(() => {
          this.$notify({
            title: 'Tips',
            message: '提交失败',
            type: 'success',
            duration: 2000
          })
        })
      } else {//当前题目做完了
        let data = {}
        data.examId = this.examInfo.id
        data.time = this.getCostTime()
        data.answers = this.userAnswer
        submitPaper(data).then((resp) => {
          if (resp.code === 200) {
            this.$notify({
              title: 'Tips',
              message: '考试结束',
              type: 'success',
              duration: 2000
            })
            this.examResult.time = data.time
            this.examResult.score = resp.data
            this.examResult.show = true
          }
        })
      }
    },
    examResultClose() {
      this.examResult.show = false
      this.getExamInfo()
    },
    nextQuestion(){
      if(this.userAnswer[this.curIndex] && !this.questionInfo[this.curIndex].done) {
        submitAnswer({ qid: this.questionInfo[this.curIndex].question.id, answer: this.userAnswer[this.curIndex] })
          .then(resp => {
            this.examInfo.dones ++;
            if(resp.data.right){
              this.examInfo.rights ++;
            }
            this.questionInfo[this.curIndex].done = true;
            this.questionInfo[this.curIndex].right = resp.data.right;
            this.questionInfo[this.curIndex].question.answer = resp.data.answer;
            this.questionInfo[this.curIndex].userAnswer = this.userAnswer[this.curIndex];
            if (this.questionInfo[this.curIndex].right) {
              if(this.curIndex + 1 <= this.questionInfo.length){
                this.curIndex++
              }
            }
          });
      }else {
        this.curIndex++
      }
    },
    getOptClass(curIndex ,item){
      let ql = this.questionInfo;
      if(this.questionInfo[curIndex].done){
        if(this.questionInfo[curIndex].right){
          if(matchOpt(this.questionInfo[curIndex].userAnswer ,item)){
            return 'right';
          }
        }else {
          if(matchOpt(this.questionInfo[curIndex].userAnswer ,item)){
            return 'error';
          }
        }
      }else {
        return matchOpt(this.userAnswer[curIndex] ,item) ? 'active' : '';
      }
      return '';

      function matchOpt(answer ,item){
        if(!answer) return false;
        if(ql[curIndex].question.type === 2){
          let arr = answer.split(",");
          return arr.indexOf(item) > -1;
        }else {
          return answer == item;
        }
      }
    },
    getQuestionClass(curIndex){
      if(this.questionInfo[curIndex].done){
        if(this.questionInfo[curIndex].right){
          return 'right';
        }else {
          return 'error'
        }
      }else if(this.userAnswer[curIndex]){
        return 'done'
      }else if(curIndex == this.curIndex){
        return 'orange'
      }
      return ''
    },
    secToTime(s) {
      var t = ''
      if (s > -1) {
        var hour = Math.floor(s / 3600)
        var min = Math.floor(s / 60) % 60
        var sec = s % 60
        if (hour < 10) {
          t = '0' + hour + ':'
        } else {
          t = hour + ':'
        }
        if (min < 10) {
          t += '0'
        }
        t += min + ':'
        if (sec < 10) {
          t += '0'
        }
        t += sec
      }
      return t
    }

  },
  watch: {
    //监控考试的剩余时间
    async duration(newVal) {
      const examDuration = {
        duration: newVal,
        timestamp: Date.now()
      }
      localStorage.setItem('examDuration' + this.examInfo.examId, JSON.stringify(examDuration))
      //摄像头数据
      let constraints = {
        video: {
          width: 200,
          height: 200
        },
        audio: false
      }
      //通过调用摄像头判断用户是否中途关闭摄像头
      // let promise = navigator.mediaDevices.getUserMedia(constraints)
      // promise.catch((back) => {
      //   this.cameraOn = false
      // })
      // if (!this.cameraOn) {//如果摄像头未开启,就再次调用开启
      //   this.getCamera()
      // }
      //考试时间结束了提交试卷
      if (newVal < 1) {
        if (this.cameraOn) {
          //结束的时候拍照上传一张
          await this.takePhoto()
          this.closeCamera()
        }
        let data = {}
        data.questionIds = []
        data.userAnswers = this.userAnswer.join('-')
        this.questionInfo.forEach((item, index) => {
          data.questionIds.push(item.questionId)
          //当前数据不完整,用户回答不完整(我们自动补充空答案,防止业务出错)
          if (index > this.userAnswer.length) {
            data.userAnswers += ' -'
          }
        })
        //如果所有题目全部未答
        if (data.userAnswers === '') {
          this.questionInfo.forEach(item => {
            data.userAnswers += ' -'
          })
          data.userAnswers.split(0, data.userAnswers.length - 1)
        }
        data.examId = parseInt(this.$route.params.examId)

        data.questionIds = data.questionIds.join(',')
        data.creditImgUrl = this.takePhotoUrl.join(',')
        exam.addExamRecord(data).then((resp) => {
          if (resp.code === 200) {
            this.$notify({
              title: 'Tips',
              message: '考试时间结束,已为您自动提交 *^▽^*',
              type: 'success',
              duration: 2000
            })
            this.$router.push('/examResult/' + resp.data)
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../assets/styles/examPage";
</style>
